package com.boarsoft.boar.deploy.plan.biz;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.boarsoft.bean.ReplyInfo;
import com.boarsoft.boar.common.Constants;
import com.boarsoft.boar.deploy.entity.BuildPlanItem;
import com.boarsoft.boar.deploy.entity.LibDeployInfo;
import com.boarsoft.boar.deploy.plan.PlanItemBiz;
import com.boarsoft.boar.deploy.plan.PlanLibBiz;
import com.boarsoft.common.Util;
import com.boarsoft.common.dao.PagedResult;
import com.boarsoft.hibernate.biz.SimpleBizImpl;

@Component("planLibBizImpl")
public class PlanLibBizImpl extends SimpleBizImpl implements PlanLibBiz {
	@Autowired
	private PlanItemBiz planItemBiz;

	@Override
	@Transactional
	public ReplyInfo<Object> save(BuildPlanItem o) {
		String libId = o.getTargetId();
		LibDeployInfo lib = dao.get(LibDeployInfo.class, libId);
		if (lib == null) {
			return Constants.REPLY_ERROR_NOTFOUND;
		}
		o.setCode(lib.getCode());
		o.setName(lib.getName());
		o.setPlanId(o.getPlanId());
		o.setTargetId(o.getTargetId());
		o.setType(BuildPlanItem.TYPE_LIB);
		o.setVer(lib.getVer());
		o.setMemo(lib.getMemo());
		planItemBiz.save(o);
		return ReplyInfo.SUCCESS;
	}

	/**
	 * 根据planId查询planId关联的targetId,排除这部分targetId相关的信息，返回剩余符合条件的List<AppInfo>
	 */
	@Override
	@Transactional(readOnly = true)
	public PagedResult<LibDeployInfo> list(String projId, String planId, boolean in, String key, String orderBy, int pageNo,
			int pageSize) {
		StringBuilder sb = new StringBuilder();
		sb.append(" from ").append(LibDeployInfo.class.getName())//
				.append(" a where 1=1");
		if (Util.strIsNotEmpty(projId)) {
			sb.append(" and a.projId='").append(projId).append("'");
		}
		sb.append(" and a.id ").append(in ? "in" : "not in")//
				.append(" (select t.targetId from ").append(BuildPlanItem.class.getName())//
				.append(" t where t.planId='").append(planId).append("' and type=")//
				.append(BuildPlanItem.TYPE_APP).append(")").toString();
		if (Util.strIsNotEmpty(key)) {
			sb.append(" and (a.code like '%").append(key);
			sb.append("%' or a.name like '%").append(key);
			sb.append("%' or a.memo like '%").append(key);
			sb.append("%')");
		}
		int total = dao.getTotal("select count(a.id)".concat(sb.toString()));
		List<LibDeployInfo> lt = dao.list("select a".concat(sb.toString()), pageNo, pageSize);
		return new PagedResult<LibDeployInfo>(total, lt, pageNo, pageSize);
	}
}